using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using net_work.Common.Result;
using net_work.IService.ISystem;
using LoginRequest = net_work.Common.Request.LoginRequest;

namespace net_work.Controllers.System;

[Route("api/[controller]")]
[ApiController]
public class AuthController(ILogger<AuthController> logger, IAuthService authService)
    : ControllerBase
{
    /// <summary>
    /// 登录
    /// </summary>
    /// <param name="request">登录请求</param>
    /// <returns>登录结果</returns>
    [AllowAnonymous]
    [HttpPost("login")]
    public async Task<IActionResult> Login([FromBody] LoginRequest request)
    {
        logger.LogInformation("用户登录请求");

        var validateCaptcha = await authService.ValidateCaptcha(request.CaptchaId, request.Captcha);
        if (!validateCaptcha)
        {
            return AjaxResult.Error("验证码错误！");
        }

        var loginResult = await authService.Authenticate(request);
        return loginResult == null ? AjaxResult.Error("用户名或密码错误！") : AjaxResult.Success(loginResult);
    }

    /// <summary>
    /// 刷新 Access Token
    /// </summary>
    /// <param name="refreshToken">refreshToken</param>
    /// <returns>新的 Access Token 和 Refresh Token</returns>
    [AllowAnonymous]
    [HttpPost("refresh_token")]
    public async Task<IActionResult> RefreshToken([FromBody] string refreshToken)
    {
        logger.LogInformation("用户请求刷新 Token");

        var loginResult = await authService.RefreshToken(refreshToken);
        return loginResult == null ? AjaxResult.Error("Token 刷新失败！") : AjaxResult.Success(loginResult);
    }

    /// <summary>
    /// 注销
    /// </summary>
    /// <param name="refreshToken">refreshToken</param>
    /// <returns>状态</returns>
    [AllowAnonymous]
    [HttpPost("logout")]
    public async Task<IActionResult> Logout([FromBody] string refreshToken)
    {
        logger.LogInformation("用户注销");
        await authService.Logout(refreshToken);
        return AjaxResult.Success();
    }
}